<!--
 * @Author: Lee
 * @Date: 2023-07-15 21:27:58
 * @LastEditors: Lee
 * @LastEditTime: 2023-07-15 21:37:38
 * @Description: 
-->
<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>009：数组扁平化</title>
</head>

<body>
  <script>
    const arr = [1, [2, [3, [4, 5]]], 6];

    // 1. flat()
    console.log(arr.flat(3))

    // 2. 正则表达式
    console.log(JSON.stringify(arr).replace(/\[|\]/g, '').split(",").map(item => +item))

    // 3. reduce
    function flatten(arr) {
      return arr.reduce((prev, cur) => {
        return prev.concat(Array.isArray(cur) ? flatten(cur) : cur);
      }, []);
    }
    console.log(flatten(arr))

    // 4. 递归
    const result = [];
    function fn(arr) {
      for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
          fn(arr[i])
        } else {
          result.push(arr[i]);
        }
      }
    }
    fn(arr);
    console.log(result);


  </script>
</body>

</html>